import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueDevTools(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    // 自动导入Element Plus组件
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
  server: {
    proxy: {
      // 代理后端 API
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        // 保持路径不变，将 /api 前缀一并转发到后端
        // 将后端返回的绝对重定向地址改为相对地址，避免浏览器跨域跟随
        configure: (proxy) => {
          proxy.on('proxyRes', (proxyRes) => {
            const location = proxyRes.headers['location'] as string | undefined;
            if (location && location.startsWith('http://localhost:8080')) {
              try {
                const u = new URL(location);
                proxyRes.headers['location'] = u.pathname + u.search + u.hash;
              } catch {
                // ignore invalid URL
              }
            }
          });
        },
      },
      // 某些后端（如 Spring Security）会重定向到 /login
      // 这里直接将 /login 也代理到后端，配合上面的 Location 重写可避免 CORS
      '/login': {
        target: 'http://localhost:8080',
        changeOrigin: true,
      },
    },
  }
})
